package com.chang.bootplus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chang.bootplus.base.exception.BusException;
import com.chang.bootplus.base.utils.ApiResponse;
import com.chang.bootplus.base.utils.BeanUtil;
import com.chang.bootplus.entity.*;
import com.chang.bootplus.mapper.MatrixShopcartMapper;
import com.chang.bootplus.po.*;
import com.chang.bootplus.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chang.bootplus.vo.ShopCartVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ning
 * @since 2022-01-25
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MatrixShopcartServiceImp extends ServiceImpl<MatrixShopcartMapper, MatrixShopcart> implements MatrixShopcartService {

    final MatrixShopcartMapper matrixShopcartMapper;
    final MatrixOrderService matrixOrderService;
    final ProductService productService;
    final UserLocationService userLocationService;
    final ProductDetailsService productDetailsService;
    final ProductPicturesService productPicturesService;
    final ProductCatesDetailsService productCatesDetailsService;

    @Override
    public ApiResponse<Void> addShopCart(ShopCartPO po) {
        MatrixShopcart shopCart = BeanUtil.beanA2beanB(po, MatrixShopcart.class);
        boolean b = save(shopCart);
        if(!b){
            throw new BusException("添加失败");
        }

        return new ApiResponse().setReMsg("添加成功");
    }

    @Override
    public ApiResponse<Void> updateShopCart(ShopCartListPO po) {
        MatrixShopcart shopCart = BeanUtil.beanA2beanB(po, MatrixShopcart.class);
        boolean b = updateById(shopCart);
        if(!b){
            throw new BusException("更新失败");
        }

        return new ApiResponse().setReMsg("更新成功");
    }

    @Override
    public ApiResponse<Void> deleteShopCart(ShopCartIdPO po) {
        if(po.getUserId() == null){
            boolean b1 = removeById(po.getId());
            if(!b1){
                throw new BusException("删除失败");
            }
        }
        else{
            boolean b2 = remove(new LambdaQueryWrapper<MatrixShopcart>().eq(MatrixShopcart::getUserId, po.getUserId()));
            if(!b2){
                throw new BusException("删除失败");
            }
        }
        return new ApiResponse().setReMsg("删除成功");
    }

    @Override
    public ApiResponse<ShopCartVO> listShopCart(ShopCartSelPO po) {
        po.setPageNumber(po.getPageNumber()-1);
        List<MatrixShopcart> shopCarts = matrixShopcartMapper.listShopCart(po);
        if(shopCarts==null){
            throw new BusException("查询到的购物车内容为空");
        }
        List<ShopCartVO> shopCartVOS = BeanUtil.listA2ListB(shopCarts, ShopCartVO.class);

        shopCartVOS.stream().forEach(shopCartVO -> {

            //  下面四个过程是设置商品的详情和商品的图片
            List<ProductDetails> list1 = productDetailsService.list(new LambdaQueryWrapper<ProductDetails>()
                    .eq(ProductDetails::getProId, shopCartVO.getProId()));
            Map<String, String> collect1 = list1.stream().collect(Collectors.toMap(productDetails ->
                            productCatesDetailsService.getOne(new LambdaQueryWrapper<ProductCatesDetails>()
                                    .eq(ProductCatesDetails::getId,productDetails.getProCateDetailId())).getMessage(),
                    ProductDetails::getMessage));

            List<ProductPictures> list2 = productPicturesService.list(new LambdaQueryWrapper<ProductPictures>()
                    .eq(ProductPictures::getProId, shopCartVO.getProId()));
            List<String> collect2 = list2.stream().map(a -> a.getPictureUrl()).collect(Collectors.toList());

            shopCartVO.setMapDetails(collect1).setListPictures(collect2);
        });

        return new ApiResponse<>(shopCartVOS);
    }

    @Override
    public ApiResponse<Void> payShopCart(ShopCartPayPO po) {
        List<Long> ids = po.getIds();
        ids.stream().forEach(id ->{
            MatrixShopcart cart = getById(id);
            if(cart.getPayStatus().equals(1)){
                throw new BusException("结算的内容出现已经结算过的内容");
            }
            cart.setPayStatus(1);
            OrderPO orderPO = new OrderPO();

            List<OrderDetailPO> detailsList = new ArrayList<>();
            detailsList.add(new OrderDetailPO().setCost(cart.getAmount())
                    .setCount(cart.getCount())
                    .setProId(cart.getProId())
            );
            orderPO.setMessage(productService.getById(cart.getProId()).getMessage())
                    .setUserId(cart.getUserId())
                    .setBusId(productService.getById(cart.getProId()).getUserId())
                    .setAmount(cart.getAmount())
                    .setUserLocationId(userLocationService.getOne(new LambdaQueryWrapper<UserLocation>()
                                    .eq(UserLocation::getUserId , cart.getUserId())).getId())
                    .setBusLocationId(userLocationService.getOne(new LambdaQueryWrapper<UserLocation>()
                            .eq(UserLocation::getUserId ,productService.getById(cart.getProId()).getUserId())).getId())
                    .setDetailsList(detailsList);
            boolean b = updateById(cart);
            if(!b){
                throw new BusException("更新购物车状态出现错误");
            }
            matrixOrderService.addOrder(orderPO);

        });

        return new ApiResponse().setReMsg("结算成功");
    }


}
